package com.edu.controller.front;

import com.edu.component.PageBean;
import com.edu.component.QueryParam;
import com.edu.service.PaperService;
import com.edu.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping("/Front")
public class IndexController {
    @Autowired
    private PaperService paperService;

    /*
        1.跳转学生注册页(视图)
        a.映射地址: /gotoRegPage [GET]
        b.内部转发: front/regIndex
        Link: /Front/gotoRegPage
     */
    @GetMapping("/gotoRegPage")
    public String gotoRegPage(){
        return "front/regIndex";
    }

    /*
        2.跳转学生登录页(视图)
        Link: /Front/login
        映射地址: /login
        内部转发: front/loginIndex
     */
    @GetMapping("/login")
    public String login(){
        return "front/loginIndex";
    }

    /*
       4.1、获取验证码.
        入参: HttpSession, HttpServletResponse
        映射地址: /getCode [GET]
     */
    @GetMapping("/getCode")
    public void getCode(HttpSession session, HttpServletResponse resp)
            throws IOException {
        //1.生成验证码(工具类)
        Map<String, Object> map = CodeUtils.generateCodeAndPic();
        //2.从Map中取出验证码(字符串)
        Object codeStr = map.get("code");
        //3.从Map中取出验证码(图片)
        BufferedImage codePic =(BufferedImage) map.get("codePic");
        //4.把验证码设置到会话域
        session.setAttribute("code",codeStr);
        //5.设置响应头信息
        setHeader( resp );
        //6.获取输出流
        OutputStream sos = resp.getOutputStream();
        //7.把图片写入输出流
        ImageIO.write(codePic,"jpeg",sos);
    }

    /*
       4.2、设置响应头部.
        入参: HttpServletResponse
     */
    private void setHeader(HttpServletResponse resp){
        //{1}验证码的图片不缓存 [http 旧版本]。
        resp.setHeader("Prama","no-cache");
        //{2}验证码的图片不缓存 。
        resp.setHeader("Cache-Control","no-cache");
        //{3}设置过期时间: 即时过期。
        resp.setDateHeader("Expires",-1);
        //{4}图片内容格式: jpeg。
        resp.setContentType("image/jpeg");

    }


    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("papers",paperService.queryAll());
        return "front/frontIndex";
    }

    @GetMapping("/paperIndex/listPage")
    @ResponseBody
    public PageBean listPage(HttpServletRequest req){
        QueryParam param = new QueryParam(req);
        return paperService.listPage( param );
    }

}

